package maosy.word.reader.impl

import maosy.word.reader.WordReader
import org.apache.commons.lang3.StringUtils
import java.io.*
import java.lang.StringBuilder
import javax.mail.Header
import javax.mail.Multipart
import javax.mail.Session
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage

class JOBReader : WordReader {

    override fun readContent(file: File): String? = read(FileInputStream(file))

    override fun readContent(path: String): String? = read(FileInputStream(File(path)))

    private fun read(inputStream: FileInputStream): String? {
        val mailSession = Session.getDefaultInstance(System.getProperties(), null)
        val msg = MimeMessage(mailSession, inputStream)
        if (msg.content is Multipart) {
            (msg.content as Multipart).apply {
                val part: MimeBodyPart = this.getBodyPart(0) as MimeBodyPart
                val strEncoding = getEncoding(part)
                return getHtmlText(part, strEncoding)
            }
        }
        return null
    }

    private fun getHtmlText(part: MimeBodyPart, encoding: String): String {
        val encode = if (StringUtils.equals(encoding, "")) "gbk" else encoding
        val reader = BufferedReader(InputStreamReader(part.inputStream, encode))
        val htmlBuilder = StringBuilder("")
        reader.lines().forEach {
            htmlBuilder.append(it).append("\r\n")
        }
        return htmlBuilder.toString()
    }


    private fun getEncoding(part: MimeBodyPart): String {
        part.allHeaders.iterator().forEach {
            val head: Header = it as Header
            println(head.name + "=" + head.value)
            if (head.name == "Content-Type") {
                val strType = head.value
                val pos = strType.indexOf("charset=")
                if (pos >= 0) {
                    var strEncoding = strType.substring(
                        pos + 8,
                        strType.length
                    )
                    if (strEncoding.startsWith("\"") || strEncoding.startsWith("\'")) {
                        strEncoding = strEncoding.substring(
                            1,
                            strEncoding.length
                        )
                    }
                    if (strEncoding.endsWith("\"") || strEncoding.endsWith("\'")) {
                        strEncoding = strEncoding.substring(
                            0,
                            strEncoding.length - 1
                        )
                    }
                    if (strEncoding.toLowerCase().compareTo("gb2312") == 0) {
                        strEncoding = "gbk"
                    }
                    return strEncoding
                }
            }
        }
        return ""
    }
}